import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
import MainComp from "../components/MainComp.vue";
import Recipe from '@/views/RecipeView'
import { getUserInfo } from "@/api/user";
import store from '@/store'
import { MessageBox } from 'element-ui'

Vue.use(VueRouter);


const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    children: [
      {
        path: '',
        name: 'home',
        title: '首页',
        component: MainComp
      },
      {
        path: 'recipe',
        title: '菜谱大全',
        name: 'recipe',
        component: Recipe
      },
      {
        path: 'detail',
        name: 'detail',
        title: '菜谱详情',
        component: () => import('@/views/DetailView')
      },
      {
        path: 'user/space',
        name: 'userspace',
        title: '个人空间',
        meta: {
          auth: true, // 登录后才可以访问
        },
        component: () => import('@/views/space/UserSpaceView'),
        redirect: {// 访问个人空间时 默认访问 works , 重定向到works
          name: 'works'
        },
        children: [
          { path: 'works', name: 'works', title: "个人作品", component: () => import('@/views/space/works') },
          { path: 'collection', name: 'collection', title: "收藏作品", component: () => import('@/views/space/works') },
          { path: 'fans', name: 'fans', title: "粉丝", component: () => import('@/views/space/fans') },
          { path: 'following', name: 'following', title: "关注", component: () => import('@/views/space/fans') },
        ]
      },
      {
        path: 'user/edit',
        name: 'edit',
        title: '编辑个人资料',
        meta: {
          aurh: true
        },
        component: () => import('@/views/space/edit')
      },
      {
        path: 'create',
        name: 'create',
        title: '添加菜谱',
        meta: { auth: true },
        component: () => import('@/views/create/CreateFoods.vue')
      },
      {
        path: 'login',
        name: 'login',
        title: '登陆注册',
        component: () => import('@/views/user')
      },
    ]
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 解决 element-ui 导航菜单重复点击报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {

  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach(async (to, from, next) => {
  // console.log(to)
  // 获取token 
  // const token = window.localStorage.getItem('token')
  // 获取用户信息 （成功/失败）
  const res = await getUserInfo()
  // 将用户信息同步到store 中
  store.commit('changeUserInfo', res.data);
  // 判断要访问的路由
  if (to.meta.auth) {
    // 判断登陆状态可以正常访问
    if (res.code == 0) { // 获取用户信息成功
      next()
    } else {
      MessageBox.alert('请登录')
      next('/login')
      // 没有登录 登陆过期
    }

  } else {
    next()
  }
  // 未登录状态 token过期 跳转到登录页面
})

export default router;
